/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.zhy.swing;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 *
 * @author Moon
 */
public class DragSupport {

    static class DragEvent extends MouseAdapter {

        private Point mouseLoc;
        private Point compLoc;

        @Override
        public void mousePressed(MouseEvent e) {
            Component comp = e.getComponent();
            if (!comp.isEnabled()) {
                return;
            }
            mouseLoc = e.getLocationOnScreen();
            compLoc = e.getComponent().getLocation();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            mouseLoc = null;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            Component comp = e.getComponent();
            if (!comp.isEnabled()) {
                return;
            }
            Point newMouseLoc = e.getLocationOnScreen();
            e.getComponent().setLocation(compLoc.x + newMouseLoc.x - mouseLoc.x,
                    compLoc.y + newMouseLoc.y - mouseLoc.y);
        }
    }

    public static void startDrag(Component comp) {
        stopDrag(comp);
        DragEvent de = new DragEvent();
        comp.addMouseListener(de);
        comp.addMouseMotionListener(de);
    }

    public static void stopDrag(Component comp) {
        for (MouseListener listener : comp.getListeners(MouseListener.class)) {
            if (listener instanceof DragEvent) {
                comp.removeMouseListener(listener);
            }
        }
        for (MouseMotionListener listener : comp.getListeners(MouseMotionListener.class)) {
            if (listener instanceof DragEvent) {
                comp.removeMouseMotionListener(listener);
            }
        }
    }
}
